<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="退款单" prop="outRefundNo">
        <el-input
          v-model="queryParams.outRefundNo"
          placeholder="请输入退款单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入手机号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="车牌号" prop="carNum">
        <el-input
          v-model="queryParams.carNum"
          placeholder="请输入车牌号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="退款状态" prop="refundState">
        <el-select v-model="queryParams.refundState" placeholder="请选择退款状态" clearable size="small">
          <el-option
            v-for="dict in refundStateOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="退款类型" prop="refundType">
        <el-select v-model="queryParams.refundType" placeholder="请选择退款类型" clearable size="small">
          <el-option
            v-for="dict in refundTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="审核状态" prop="auditState">
        <el-select v-model="queryParams.auditState" placeholder="请选择审核状态" clearable size="small">
          <el-option
            v-for="dict in auditStateOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="refundList" >
      <el-table-column label="手机号" align="center" prop="mobile"/>
      <el-table-column label="车牌号" align="center" prop="carNum"/>
      <el-table-column label="退款单" align="center" prop="outRefundNo"/>
      <el-table-column label="退款金额" align="center" prop="refundAmount"/>
      <el-table-column label="扣款金额" align="center" prop="chargeAmount"/>

      <el-table-column label="退款状态" align="center" prop="refundState" :formatter="refundStateFormat"/>
      <el-table-column label="退款类型" align="center" prop="refundType" :formatter="refundTypeFormat"/>
      <el-table-column label="审核状态" align="center" prop="auditState" :formatter="auditStateFormat"/>
      <el-table-column label="退款原因" align="center" prop="reason"/>
      <el-table-column label="支付渠道" align="center" prop="payChannel"/>
      <el-table-column label="订单号" align="center" prop="orderNo"/>
      <el-table-column label="订单金额" align="center" prop="orderPrice"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="创建时间" align="center" prop="gmtTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.gmtTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center"  fixed="right"  width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.auditState === 1 && (scope.row.refundState === 0 || scope.row.refundState === 2)"
            v-hasPermi="['order:refund:query']"
          >查询
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleAudit(scope.row)"
            v-if="scope.row.refundType === 2 && scope.row.auditState === 0"
            v-hasPermi="['order:refund:audit']"
          >审核
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleOnline(scope.row)"
            v-if="scope.row.auditState === 1 && (scope.row.refundState != 1)"
            v-hasPermi="['order:refund:refund']"
          >退款
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleManu(scope.row)"
            v-if="scope.row.auditState === 1 && (scope.row.refundState != 1)"
            v-hasPermi="['order:refund:refund']"
          >线下打款
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" :visible.sync="auditOpen" width="500px">
      <el-row class="order_detail">
        <el-col :span="12">订单实付: {{curItem.orderPrice}}</el-col>
        <el-col :span="12">原扣款金额: {{curItem.chargeAmount || 0}}
          <el-button v-if="isChg" type="primary" size="mini" @click="doRollBack">还原</el-button>
          <el-button v-else type="warning" size="mini" @click="doChgAmount">修改</el-button>
        </el-col>
      </el-row>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item v-if="isChg" label="扣款金额" prop="state">
          <el-select v-model="form.chargeAmount" placeholder="请选择扣款金额" clearable size="small">
            <el-option
              v-for="dict in orderChargeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="审核结果" prop="state">
          <el-select v-model="form.auditState" placeholder="请选择审核结果" clearable size="small">
            <el-option
              v-for="dict in auditState"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="审核备注" prop="auditReason">
          <el-input
            v-model="form.auditReason"
            placeholder="为防止金额纠纷，请填写审核备注，（审核通过默认备注为：审核通过）"
            clearable
            size="small"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRefundAudit">确 定</el-button>
        <el-button @click="auditOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 线下打款对话框 -->
    <el-dialog title="线下打款" :visible.sync="manuopen" v-if="manuopen" width="40%" v-dialogdrag append-to-body>
        <el-upload
          class="avatar-uploader"
          :action="action"
          :headers="headers"
          :show-file-list="false"
          :on-success="handleTransferVoucherSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="transferVoucher" :src="transferVoucher" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      <el-row class="remark">
        <p>备注：</p>
        <p>1、为防止退款交易纠纷，打款凭证必传</p>
        <p>2、打款操作不可逆，请确保无误后再执行【确定打款】操作</p>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button   @click="manuopen = false">取消打款</el-button>
        <el-button type="primary"  @click="manuSubmit">确定打款</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {
    listRefund,
    manuRefund,
    onlineRefund,
    auditRefund,
    queryRefund,
    preCheckRefund
  } from "@/api/order/refund";
  import defaultSettings from '@/settings'
  import {mapGetters} from "vuex";

  export default {
    name: "Refund",
    data() {
      return {
        auditOpen: false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        isChg: false,
        // 总条数
        total: 0,
        // 退款记录表格数据
        refundList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        manuopen: false,
        // 退款状态字典
        refundStateOptions: [],
        refundTypeOptions: [],
        auditStateOptions: [],
        orderChargeOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          orderId: undefined,
          memberId: undefined,
          outRefundNo: undefined,
          orderNo: undefined,
          mobile: undefined,
          carNum: undefined,
          tradeNo: undefined,
          outTradeNo: undefined,
          refundAmount: undefined,
          orderPrice: undefined,
          gmtTime: undefined,
          refundState: undefined,
          auditState: undefined,
          refundType: undefined,
          payChannel: undefined,
          title: undefined
        },
        // 表单参数
        form: {
          id: undefined,
          auditReason: undefined,
          auditState: '',
          chargeAmount: undefined
        },
        curItem: {},
        auditState: [{
          label: '审核通过',
          value: '1'
        }, {
          label: '审核拒绝',
          value: '2'
        }],
        // 表单校验
        rules: {},
        action:process.env.VUE_APP_BASE_API + '/common/upload/oss',
        imgpre: defaultSettings.ossPreview,
        transferVoucher: '',
        manuForm: {
          id: undefined,
          transferVoucher: undefined,
        }
      };
    },
    computed: {
      ...mapGetters(['token']),
      headers() {
        return{
          "Authorization": this.token // 直接从本地获取token就行
        }
      }
    },
    created() {
      this.getDicts("refund_state").then(response => {
        this.refundStateOptions = response.data;
      });
      this.getDicts("refund_type").then(response => {
        this.refundTypeOptions = response.data;
      });
      this.getDicts("refund_audit_state").then(response => {
        this.auditStateOptions = response.data;
      });
      this.getDicts("order_charge").then(response => {
        this.orderChargeOptions = response.data;
      });
      this.getList();
    },
    methods: {
      handleManu(row){
        this.manuopen = true;
        this.manuForm.id = row.id;
        this.manuForm.transferVoucher = '';
      },
      doRollBack() {
        this.isChg = false;
        this.form.chargeAmount = undefined
      },
      doChgAmount() {
        this.isChg = true;
      },
      /** 查询退款记录列表 */
      getList() {
        this.loading = true;
        listRefund(this.queryParams).then(response => {
          this.refundList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 退款状态字典翻译
      refundStateFormat(row, column) {
        return this.selectDictLabel(this.refundStateOptions, row.refundState);
      },
      // 退款类型字典翻译
      refundTypeFormat(row, column) {
        return this.selectDictLabel(this.refundTypeOptions, row.refundType);
      },
      // 审核状态字典翻译
      auditStateFormat(row, column) {
        return this.selectDictLabel(this.auditStateOptions, row.auditState);
      },
      // 表单重置
      reset(row) {
        this.form = {
          id: row.id,
          auditReason: undefined,
          auditState: '',
          chargeAmount: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },

      /** 查询按钮操作 */
      handleUpdate(row) {
        const id = row.id || this.ids
        queryRefund(id).then(response => {
          this.msgSuccess(response.msg);
          this.getList();
        });
      },

      /** 线上退款按钮操作 */
      handleOnline(row) {
        const id = row.id
        onlineRefund(id).then(response => {
          this.msgSuccess(response.msg);
          this.getList();
        });
      },
      /*审核按钮操作*/
      handleAudit(row) {
        this.curItem = row;
        this.reset(row);
        this.auditOpen = true;
      },
      /** 线下打款提交 */
      manuSubmit: function () {
        if (!this.manuForm.id){
          this.msgError("请选择退款记录");
          return
        }
        if (!this.manuForm.transferVoucher){
          this.msgError("请上传打款凭证");
          return
        }
        manuRefund(this.manuForm).then(response => {
          if (response.code === 200) {
            this.msgSuccess("操作成功");
            this.manuopen = false;
            this.getList();
          } else {
            this.msgError(response.msg);
          }
        });
      },
      /** 部分退款提交操作 */
      submitRefundAudit() {
        const data = this.form
        let that = this;
        if (!data.auditState){
          this.msgError("请选择审核结果");
          return
        }
        if (!data.auditReason){
          this.msgError("为防止金额纠纷，请填写审核备注");
          return
        }
        let confirmMsg = "";
        console.log("审核状态：" + data.auditState)
        if (data.auditState === '1' ){
          if (this.form.chargeAmount){
            confirmMsg = "原扣款金额为" + this.curItem.chargeAmount + "元，现修改为扣款"+ data.chargeAmount + "元，是否确认金额无误，并执行退款操作？"
          }else{
            confirmMsg = "原扣款金额为" + this.curItem.chargeAmount + "元，您未修改退款金额，是否确认金额无误，并执行退款操作？"
          }
        }else{
            confirmMsg = "您拒绝了退款申请，是否确认操作无误？";
        }

        this.$confirm(confirmMsg, "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
            if (data.auditState === '1' ){
              that._doPreCheckRefund(data);
            }else{
              that._doAuditRefund(data)
            }
        }).catch(function () {
        });
      },
      _doPreCheckRefund(data){
        preCheckRefund("refund",data.id).then(res => {
          if (res.subCode && res.subCode == 500){
            this.$confirm(res.msg, '提示', {
              confirmButtonText: '金额无误，继续退款',
              cancelButtonText: '我要重新审核',
              type: 'warning'
            }).then(() => {
              this._doAuditRefund(data)
            }).catch(() => {
            });
          }else{
            this._doAuditRefund(data)
          }
        });
      },
      _doAuditRefund(data){
        auditRefund(data).then(response => {
          if (response.code === 200) {
            this.auditOpen = false;
            this.getList();
            this.msgSuccess(response.msg);
          } else {
            this.msgError(response.msg);
          }
        });
      },
      handleTransferVoucherSuccess(res, file) {
        this.transferVoucher = this.imgpre + res.imgUrl;
        this.manuForm.transferVoucher = res.imgUrl;
      },
      beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (file.type.indexOf("image/") == -1) {
          this.$message.error('文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。');
          return
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
          return
        }
      },
    }
  };
</script>
<style>
  .order_detail{
    padding-left: 12px;
    font-size: 16px;
    margin-bottom: 20px;
    font-weight: 700;
    color: red;
  }


  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 200px;
    height: 200px;
    line-height: 200px;
    text-align: center;
  }
  .avatar {
    width: 200px;
    height: 200px;
    display: block;
  }
</style>
